package com.zsj.qzt_punch.script;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zsj.qzt_punch.http.QztHttpRequest;
import com.zsj.qzt_punch.pojo.MonthReportRequestBody;
import com.zsj.qzt_punch.pojo.QztTokenInfo;
import com.zsj.qzt_punch.pojo.Result;
import com.zsj.qzt_punch.pojo.WeekReportRequestBody;
import com.zsj.qzt_punch.service.QztTokenInfoService;
import com.zsj.qzt_punch.util.SendEmail;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * @author zsj
 * 发送周报,月报
 */
@Component
@Slf4j
@Configuration
@EnableScheduling
public class ReportScript {


    @Autowired
    QztTokenInfoService qztTokenInfoService;
    Calendar calendar;


    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//时间格式化工具

    /**
     * 定时器 发送周报
     * 每年的每月的每周的周五下午5点提交周报
     */
    @Scheduled(cron = "0 0 17 ? * FRI")
    public void sendWeekReport() throws InterruptedException {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(QztHttpRequest.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        calendar = Calendar.getInstance();
        QztHttpRequest qztHttpRequest = retrofit.create(QztHttpRequest.class);
        WeekReportRequestBody weekReportRequestBody = new WeekReportRequestBody();
        weekReportRequestBody.setContent("周报内容");
        weekReportRequestBody.setEnterpriseId("企业id");
        int month = calendar.get(Calendar.MONTH) + 1;//第几月
        int year = calendar.get(Calendar.YEAR);//年
        int week = calendar.get(Calendar.WEEK_OF_MONTH);//第几周
        weekReportRequestBody.setWorkMonth(String.valueOf(month));//月
        weekReportRequestBody.setWorkWeek(week);//周
        weekReportRequestBody.setWorkYear(year);//年
        weekReportRequestBody.setFileList(new ArrayList<>());
        weekReportRequestBody.setTeacherId("指导教师id");
        weekReportRequestBody.setRemarks("");
        weekReportRequestBody.setTitle(year + "年" + month + "月第" + week + "周周报");
        QueryWrapper<QztTokenInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", "数据库字典");
        qztHttpRequest.submitDataByWeekly(qztTokenInfoService.getOne(wrapper).getTokenValue(), weekReportRequestBody)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create();
                        if (response.body() != null) {
                            try {
                                Result result = gson.fromJson(response.body().string(), Result.class);
                                if (null != result) {
                                    String msg = result.getMsg();
                                    log.info(msg);
                                    try {
                                        if (msg.contains("提交成功")) {
                                            SendEmail.sendEmail(msg + "发送时间为" + format.format(new Date())
                                                    + ",\n\n\n\n------来自zsj的ReportScript程序");
                                            log.info("周报提交成功~~");
                                        } else {
                                            log.error("周报提交失败,msg{}", msg);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException(e);
                                    }
                                } else {
                                    log.warn("周报发送出现错误");
                                }
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                        log.error(throwable.getMessage());
                    }
                });

    }


    /**
     * 定时器 发送月报
     * 每个月的最后一天早上八点发送
     */
    @Scheduled(cron = "0 0 8 28-31 * ?")
    public void sendMonthReport() {
        calendar = Calendar.getInstance();
        if (calendar.get(Calendar.DATE) != calendar.getActualMaximum(Calendar.DATE)) {
            //说明不是最后一天
            log.warn("今天是这个月的第"
                    + calendar.get(Calendar.DATE) + "天,不是最后一天,最后一天应该为" +
                    calendar.getActualMaximum(Calendar.DATE));
            log.warn("降级~~~~~~~~~取消执行~~~~");
        } else {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(QztHttpRequest.baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            QztHttpRequest request = retrofit.create(QztHttpRequest.class);
            MonthReportRequestBody requestBody = new MonthReportRequestBody();
            int month = calendar.get(Calendar.MONTH) + 1;//月
            int year = calendar.get(Calendar.YEAR);//年
            requestBody.setWorkYear(2022);
            requestBody.setWorkMonth(String.valueOf(month));
            requestBody.setTitle(year + "年" + month + "月月报");
            requestBody.setContent("月报内容");
            requestBody.setEnterpriseId("企业id");
            requestBody.setTeacherId("教师id");
            requestBody.setRemarks("备注");
            requestBody.setWorkWeek("");
            requestBody.setFileList(new ArrayList<>());
            QueryWrapper<QztTokenInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", "数据库字典中你的名字");
            request.submitDataByMonthly(qztTokenInfoService.getOne(wrapper).getTokenValue()
                    , requestBody).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create();
                    if (response.body() != null) {
                        try {
                            Result result = gson.fromJson(response.body().string(), Result.class);
                            if (result.getMsg().contains("提交成功")) {
                                //周报提交成功
                                SendEmail.sendEmail(result.getMsg() + "提交时间为" + format.format(new Date())
                                        + "来自zsj的ReportScript程序");
                                log.info("月报提交成功");
                            } else {
                                log.error(result.getMsg());
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                    log.error(throwable.getMessage());
                }
            });
        }
    }

}
